import { Component } from '@angular/core';
import {BaseInputComponent} from "@shared/base-form/base-input/base-input.component";
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../../constant/config';
import { CacheService } from '@core/routes-services/cache.service';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';

@Component({
  selector: 'base-img-input',
  templateUrl: './base-img-input.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 100px;
      height: 100px;
    }
    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }
    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
    :host ::ng-deep .ant-upload .avatar {
      width: 100px;
      height: 100px;
    }
  `]
})
export class BaseImgInputComponent extends BaseInputComponent{
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};

  fileList:any [] = [];
  previewImage = '';
  previewVisible = false;

  constructor(  private cacheService: CacheService,
                private message: NzMessageService,) {
    super();
  }

  ngOnInit(){
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    //todo 可扩展多张图情况
    if(this.validateForm.value.value){
      this.fileList.push({
        name: this.validateForm.value.name,
        url:this.validateForm.value.value
      });
    }
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.validateForm.controls.value.setValue(fileList[findIdx].url);
    }
    if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }

    if(status === 'removed'){
      this.validateForm.controls.value.setValue(null);
    }
  }


  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

}
